from fastapi import APIRouter, FastAPI
from fastapi.responses import StreamingResponse
import asyncio
from src.Controller.AppController import AppController
from src.Core.ai.chinese_bert.Intent_analysis_ai import analyze_intent
from src.Core.ai.ai_Q_A import call_model

app_controller = AppController()

class ApiRoutes:
    def __init__(self, app: FastAPI, router: APIRouter):
        # print("ApiRoutes __init__ ============================")
        self.app = app
        self.router = router
        self.app_controller = app_controller

    def setup(self):
        @self.router.get("/chat")
        async def answer_question(message: str, mode: str):
            # 0 询问意图，1 购买意图
            intent = analyze_intent(message)

            data = {
                "message": '',
                "products": []
            }

            # 模拟异步获取推荐商品，这里使用 asyncio.sleep 模拟耗时操作，你需要替换为实际的异步函数调用
            async def get_recommended_products():
                await asyncio.sleep(1)  # 模拟耗时
                if intent == 1:
                    return self.app_controller.find_similar(message)
                return []

            # 异步获取 ai 回答，这里获取的是一个生成器
            ai_answer_generator = await call_model(message, mode)

            # 定义一个生成器函数，用于流式输出数据，调整为 SSE 格式
            async def stream_data():
                async for partial_data in ai_answer_generator:
                    yield partial_data
                # 异步获取推荐商品
                recommended_products = await get_recommended_products()
                data["products"] = recommended_products
                final_json_data = {
                    "message": data["message"],
                    "products": data["products"]
                }
                final_json_str = str(final_json_data).replace("'", "\"")
                yield f"data: {final_json_str}\n\n"

            return StreamingResponse(stream_data(), media_type="text/event-stream")
        
        self.app.include_router(self.router, prefix="/api")